<?php

namespace app\virtual\admin;

use app\common\builder\ZBuilder;
use app\virtual\model\Order as OrderModel;

/**
 * 订单控制器
 */
class Order extends Index
{

    protected function initialize()
    {
        parent::initialize();
        if ($this->no_auth) {
            $this->error('权限不足！');
        }
    }

    /**
     * 首页
     * @return mixed
     */
    public function index()
    {
        // 设置搜索参数
        $search = ['address' => '地址', 'type' => '类型'];

        // 获取查询条件
        $map = $this->getMap();

        $list_rows = input('list_rows', 20) >= 20 ? 20 : input('list_rows');
        // 数据列表
        $data_list = OrderModel::where($map)->order('block_ts desc')->paginate($list_rows);
        // 分页数据
        $page = $data_list->render();

        $items = [
            ['transaction_id', '交易哈希'],
            ['block_ts', '时间', 'callback', function ($value) {
                return $value ? date("Y-m-d H:i:s", $value / 1000) : '';
            }, '', 'text-center'],
            ['from_address', '发送地址'],
            ['to_address', '接收地址'],
            ['contract_address', '合约地址'],
            ['quant', '数量'],
            ['create_time', '发起时间', 'datetime', '', 'Y-m-d H:i:s'],
            ['update_time', '完成时间', 'datetime', '', 'Y-m-d H:i:s'],
            ['right_button', '操作', 'btn']
        ];

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->hideCheckbox()
            ->setPageTitle('usdt订单') // 设置页面标题
            ->setTableName('virtual_order') // 设置数据表名
            ->setPrimaryKey('order_id') // 设置主键名为id
            ->setSearch($search) // 设置搜索参数
            ->addColumns($items)
            ->addTopButtons('add,enable,disable,delete') // 批量添加顶部按钮
            ->addRightButton('see', ['title' => '查看', 'icon' => 'fa fa-fw fa-eye', 'href' => url('see', ['id' => '__id__'])], true)
            ->addRightButtons('edit,delete') // 批量添加右侧按钮
            ->setRowList($data_list) // 设置表格数据
            ->setPages($page) // 设置分页数据
            ->fetch(); // 渲染页面
    }

    /**
     * 新增
     * @return mixed
     */
    public function add()
    {

        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();

            // 验证
            $result = $this->validate($data, 'Order');
            // 验证失败 输出错误信息
            if (true !== $result) {
                $this->error($result);
            }

            $address = $data['address'];

            $arr['start'] = '0';    // 起始编号0
            $arr['limit'] = '10'; // 每页数量10
            $arr['contract_address'] = 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t'; // 合约地址
            $arr['start_timestamp'] = ''; // 开始时间
            $arr['end_timestamp'] = ''; // 结束时间
            $arr['confirm'] = ''; // 是否只获取已确认的转账列表，默认true
            $arr['relatedAddress'] = $address; // 相关地址，账户地址
            $arr['fromAddress'] = ''; // 寄件人地址
            $arr['toAddress'] = ''; // 接收者的地址
            $arr['reverse'] = ''; // 按创建时间排序sort by create time

            $string = http_build_query($arr);
            $url = "https://apilist.tronscanapi.com/api/token_trc20/transfers?$string";

            $resdata = go_curl($url, '', 'get', 10);
            $resarray = json_decode($resdata, true);
            if ($resarray['token_transfers']) {
                foreach ($resarray['token_transfers'] as $key => $value) {
                    $data['order_id'] = date('ymdHis') . random(8);
                    $data['transaction_id'] = $value['transaction_id'];
                    $data['block_ts'] = $value['block_ts'];
                    $data['from_address'] = $value['from_address'];
                    $data['to_address'] = $value['to_address'];
                    $data['block'] = $value['block'];
                    $data['contract_address'] = $value['contract_address'];
                    $data['quant'] = $value['quant'];
                    $data['transaction_id'] = $value['transaction_id'];
                    if (OrderModel::create($data)) {
                    }
                }
            }

            $this->success('新增成功', url('index'));
        }

        $items = [
            ['text', 'address', '地址', '根据地址，统计订单列表'],
            ['text', 'sum', '数量', '总共统计最近多少数据'],
        ];

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('新增') // 设置页面标题
            ->addFormItems($items)
            ->fetch();
    }

    /**
     * 查看
     * @param null $id 
     * @return mixed
     */
    public function see($id = null)
    {
        if ($id === null) {
            $this->error('缺少参数！');
        }

        // 获取数据
        $info = UsdtModel::where('id', $id)->field(true)->find();
        if (!$info) {
            $this->error('不存在！');
        }

        if ($info['type'] == 'TRC20') {

            $address = $info['address'];
            $url = "https://apilist.tronscanapi.com/api/account/tokens?address={$address}";

            $resdata = go_curl($url, '', 'get', 10);
            $resarray = json_decode($resdata, true);
            if (isset($resarray['data'])) {
                foreach ($resarray['data'] as $key => $value) {
                    if ($value['tokenId'] == 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t') {
                        $info['cash'] = $value['balance'] / 1000000;
                    }
                }
            }
        }

        $items = [
            ['static', 'id', 'ID'],
            ['static', 'cash', '余额'],
            ['static', 'address', '地址'],
            ['static', 'type', '类型'],
            ['radio', 'cash_query', '自动查询USDT余额', '', ['禁用', '启用']],
            ['radio', 'order_query', '自动查询USDT订单', '', ['禁用', '启用']],
            ['static', 'remark', '备注'],
            ['static', 'sort', '排序'],
            ['radio', 'status', '状态', '', ['禁用', '启用']],
            ['datetime', 'create_time', '创建时间', '', '', 'YYYY-MM-DD HH:mm:ss', 'disabled'],
            ['datetime', 'update_time', '更新时间', '', '', 'YYYY-MM-DD HH:mm:ss', 'disabled'],
        ];

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('查看') // 设置页面标题
            ->addFormItems($items)
            ->hideBtn('submit')
            ->setFormData($info) // 设置表单数据
            ->fetch();
    }

    /**
     * 编辑
     * @param null $id 
     * @return mixed
     */
    public function edit($id = null)
    {
        if ($id === null) {
            $this->error('缺少参数！');
        }

        // 获取数据
        $info = UsdtModel::where('id', $id)->find();
        if (!$info) {
            $this->error('不存在！');
        }

        if ($info['type'] == 'TRC20') {

            $address = $info['address'];
            $url = "https://apilist.tronscanapi.com/api/account/tokens?address={$address}";

            $resdata = go_curl($url, '', 'get', 10);
            $info['account'] = format_nice($resdata);

            $arr['start'] = '0';    // 起始编号0
            $arr['limit'] = '10'; // 每页数量10
            $arr['contract_address'] = 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t'; // 合约地址
            $arr['start_timestamp'] = ''; // 开始时间
            $arr['end_timestamp'] = ''; // 结束时间
            $arr['confirm'] = ''; // 是否只获取已确认的转账列表，默认true
            $arr['relatedAddress'] = $address; // 相关地址，账户地址
            $arr['fromAddress'] = ''; // 寄件人地址
            $arr['toAddress'] = ''; // 接收者的地址
            $arr['reverse'] = ''; // 按创建时间排序sort by create time

            $string = http_build_query($arr);
            $url = "https://apilist.tronscanapi.com/api/token_trc20/transfers?$string";

            $resdata = go_curl($url, '', 'get', 10);
            $info['list'] = format_nice($resdata);
        }

        $items = [
            ['static', 'id', 'ID', '', $id],
            ['static', 'address', '地址'],
            ['textarea', 'account', '帐号[:无]', '', '', '', ''],
            ['textarea', 'list', '列表[:无]', '', '', '', ''],
        ];

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('信息') // 设置页面标题
            ->addHidden('id')
            ->addFormItems($items)
            ->hideBtn('submit')
            ->setFormData($info) // 设置表单数据
            ->fetch();
    }

    /**
     * 删除
     * @param array $record 
     * @return mixed
     */
    public function delete($record = [])
    {
        return $this->setStatus('delete');
    }

    /**
     * 启用
     * @param array $record 
     * @return mixed
     */
    public function enable($record = [])
    {
        return $this->setStatus('enable');
    }

    /**
     * 禁用
     * @param array $record 
     * @return mixed
     */
    public function disable($record = [])
    {
        return $this->setStatus('disable');
    }

    /**
     * 设置状态：删除、禁用、启用
     * @param string $type 类型：delete/enable/disable
     * @param array $record 
     * @return mixed
     */
    public function setStatus($type = '', $record = [])
    {
        $ids = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
        $ids_delete = is_array($ids) ? '' : $ids;
        $data = UsdtModel::where('id', 'in', $ids)->column('id');
        return parent::setStatus($type, ['virtual_usdt_' . $type, 'virtual_usdt', $ids_delete, UID, implode('、', $data)]);
    }

    /**
     * 快速编辑
     * @param array $record 行为日志
     * @return mixed
     */
    public function quickEdit($record = [])
    {
        $id = input('post.pk', '');
        $field = input('post.name', '');
        $value = input('post.value', '');
        $data = UsdtModel::where('id', $id)->value($field);
        $details = '字段(' . $field . ')，原值(' . $data . ')，新值：(' . $value . ')';
        return parent::quickEdit(['virtual_usdt_edit', 'virtual_usdt', $id, UID, $details]);
    }
}
